from django.db import models

# Create your models here.

from django.db import models

from utils.base_models import BaseModel


def get_default_global_func():
    try:
        with open('utils/global_func.py', 'r', encoding='utf-8') as f:
            return f.read()
    except Exception:  # noqa
        return ''


class Environment(BaseModel):
    name = models.CharField(verbose_name='环境名称', help_text='环境名称', max_length=50)
    host = models.CharField(verbose_name='项目主机', help_text='项目主机', max_length=50, null=True, blank=True)
    db = models.JSONField(verbose_name='数据库设置', help_text='数据库设置', default=list, null=True, blank=True)
    headers = models.JSONField(verbose_name='请求头设置', help_text='请求头设置', default=dict, null=True, blank=True)
    global_variable = models.JSONField(verbose_name='全局变量设置', help_text='全局变量设置', default=dict, null=True,
                                       blank=True)
    debug_global_variable = models.JSONField(verbose_name='调试全局变量设置', help_text='调试全局变量设置',
                                             default=dict, null=True, blank=True)
    global_func = models.TextField(verbose_name='全局函数设置', help_text='全局函数设置',
                                   default=get_default_global_func, null=True,
                                   blank=True)
    project = models.ForeignKey(verbose_name='所属项目', help_text='所属项目', to='projects.Project',
                                on_delete=models.CASCADE, related_name='environments')

    class Meta:
        db_table = 'tb_environment'
        verbose_name = 'environment'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name
